<template>
  <div class="w-screen h-screen flex items-center justify-center bg-gray-100">
    <n-card title="登录" class="w-96" content-class="w-96">
      <n-form :model="form" ref="formRef" label-placement="left" label-width="80">
        <n-form-item label="用户名" path="username">
          <n-input v-model:value="form.username" placeholder="请输入用户名" @keyup.enter="handleLogin"/>
        </n-form-item>
        <n-form-item label="密码" path="password">
          <n-input type="password" v-model:value="form.password" placeholder="请输入密码" @keyup.enter="handleLogin"/>
        </n-form-item>
        <n-form-item>
          <n-button type="primary" block @click="handleLogin" :loading="loading">
            登录
          </n-button>
        </n-form-item>
      </n-form>
    </n-card>
  </div>
</template>

<script setup>
import {ref} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {useAuthStore} from '@/store/auth'
import {authApi} from "@/api/sys/auth.js";
import {useMessage} from "naive-ui";

// 表单数据
const form = ref({
  username: '',
  password: ''
})
const formRef = ref(null)
const loading = ref(false)

// Pinia store
const authStore = useAuthStore()

// 路由
const router = useRouter()
const route = useRoute()


// 登录处理
async function handleLogin() {
  if (!form.value.username || !form.value.password) return

  loading.value = true
  try {
    const res = await authApi.login({
      username: form.value.username,
      password: form.value.password
    })
    if (res.code === 1) {
      await authStore.setToken(res.data)
      // 登录成功跳转原目标页
      const redirectPath = route.query.redirect || '/'
      await router.replace(redirectPath)
    }
  } catch (err) {
    console.error('登录失败:', err)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
/* 可选自定义样式 */
</style>
